/*
 * @Author: zhougb9 zhougb9@qq.com
 * @Date: 2025-05-21 21:00:59
 * @LastEditors: zhougb9 zhougb9@qq.com
 * @LastEditTime: 2025-05-24 22:36:15
 * @FilePath: \LibreTVe:\Code\LibreTVReact\src\pages\search\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { search, streamSearch, SearchResult } from '@/services/search';
import { getPlayDetail } from '@/services/detail';
import { Card, Row, Col, Spin, Empty, message } from 'antd';

const SearchPage: React.FC = () => {
  const useQuery = () => new URLSearchParams(useLocation().search);
  const keyword = useQuery().get('keyword') || '';
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<SearchResult[]>([]);
  const [detailLoading, setDetailLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    if (!keyword) {
      setData([]);
      return;
    }

    setLoading(true);
    setData([]); // 清空之前的数据

    const stopStream = streamSearch(
      { 
        keyword: keyword,
        page: 1,
        userId: localStorage.getItem('userId') || undefined
      },
      (result) => {
        console.log('result',result)
        switch (result.type) {
          case 'start':
            setLoading(true);
            break;
          case 'data':
            if (result.data) {
              setData(prev => [...prev, result.data!]);
            }
            break;
          case 'end':
            setLoading(false);
            break;
          case 'error':
            setLoading(false);
            message.error(result.error || '搜索出错');
            break;
        }
      }
    );

    // 组件卸载或搜索词改变时停止流
    return () => {
      stopStream();
      setLoading(false);
    };
  }, [keyword]);

  const handleCardClick = async (item: SearchResult) => {
    setDetailLoading(true);
    try {
      const res = await getPlayDetail({ vodId: item.vodId, proxyId: item.proxyId });
      navigate('/play', {
        state: Array.isArray(res.data) ? res.data[0] : res.data,
      });
    } finally {
      setDetailLoading(false);
    }

    // window.open(`/play?vodId=${item.vodId}&proxyId=${item.proxyId}`, '_blank');

  };

  return (
    <div style={{ padding: 24 }}>
      {loading ? (
        <Spin />
      ) : data.length === 0 ? (
        <Empty description="暂无结果" />
      ) : (
        <Row gutter={[24, 24]}>
          {data.map((item) => (
            <Col span={6} key={item.vodId}>
              <Card
                hoverable
                cover={
                  <img
                    src={item.vodPic}
                    alt={item.vodName}
                    style={{ height: 240, objectFit: 'cover', borderRadius: 8 }}
                  />
                }
                onClick={() => handleCardClick(item)}
                style={{ background: '#181818', color: '#fff', border: 'none', borderRadius: 12 }}
                bodyStyle={{ padding: 12 }}
              >
                <div style={{ fontWeight: 'bold', color: '#fff', fontSize: 16 }}>{item.vodName}</div>
                <div style={{ color: '#aaa', fontSize: 12, margin: '4px 0' }}>
                  <span style={{ marginRight: 8 }}>{item.typeName}</span>
                  <span>{item.vodYear}</span>
                  <span style={{ marginLeft: 8 }}>{item.vodRemarks}</span>
                </div>
                <div style={{ color: '#ffd700', fontSize: 13 }}>{item.proxyName}</div>
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
};

export default SearchPage;
